//
//  File.swift
//  CreateMyCode
//
//  Created by zhibao on 2024/2/27.
//

import UIKit
class FileDetailController: SecSuperController, UIDocumentInteractionControllerDelegate {
    var dic = [String:Any]()
    fileprivate var qrImgView = UIImageView()
    fileprivate var document:UIDocumentInteractionController!
    fileprivate var imgTempPath = ""
    
    var hisdetailNum = 0
    var editNum = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = LocalizedString("详情")
        DLog(message: "dic====\(dic)")
        
        let twoBtn = UIButton(type: .custom)
        twoBtn.frame = CGRectMake(0, 0, pixw(p:60), 60)
        twoBtn.setImage(UIImage(systemName: "highlighter"), for: .normal)
        twoBtn.tintColor = UIColor.white
        twoBtn.addTarget(self, action: #selector(navClick), for: .touchUpInside)
        
        for controller in self.navigationController!.viewControllers{
            if controller.isKind(of: FileDetailController.self) {
                hisdetailNum = hisdetailNum + 1
            }
            
            if controller.isKind(of: EditCodeController.self) {
                editNum = editNum + 1
            }
        }
        
        if hisdetailNum > 1 || editNum >= 1 {
            twoBtn.setImage(nil, for: .normal)
            twoBtn.tag = 1000
            twoBtn.setTitle(LocalizedString("完成"), for: .normal)
            twoBtn.setTitleColor(UIColor.white, for: .normal)
            twoBtn.titleLabel?.font = MY_SCALE_RegularFONT(14)
        }
        
        let item = UIBarButtonItem(customView: twoBtn)
        self.gk_navRightBarButtonItems = [item]
        
        var customPara = Helper.dictionary(withJsonString: self.dic["customParameterStr"] as? String ?? "") as? [String:Any] ?? [String:Any]()
        if customPara.keys.count < 1 {
            customPara = Helper.dictionary(withJsonString: self.dic["custom_parameters_str"] as? String ?? "") as? [String:Any] ?? [String:Any]()
        }
        let title = customPara["nav"] as? String ?? "---"
        let contentView = UIView(frame: CGRect(x: 0, y: navigationFullHeight() + pixw(p:80), width: pixw(p:315), height:pixw(p:404 -  255) + 255))
        contentView.centerX = SCREEN_WIDTH / 2
        contentView.backgroundColor = MYColor.color(withHexString: "#F3F4F8", alpha: 0.7)
        contentView.layer.cornerRadius = pixw(p: 10)
        self.view.addSubview(contentView)
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: contentView.width, height: pixw(p: 75)))
        titleView.backgroundColor = MYColor.color(withHexString: "ffffff", alpha: 0.4)
        contentView.addSubview(titleView)

        let titleLabel = UILabel()
        titleLabel.text = title
        titleLabel.font = MY_SCALE_RegularFONT(14)
        titleLabel.textColor = MYRed
        titleLabel.textAlignment = .center
        titleView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(pixw(p:20))
            make.right.equalTo(pixw(p:-20))
            make.top.equalTo(pixw(p:16))
        }
        
        let detailLabel = UILabel()
        detailLabel.text = self.dic["content"] as? String ?? "----"
        detailLabel.font = MY_SCALE_RegularFONT(10)
        detailLabel.textColor = MYColor.color(withHexString: "777777")
        detailLabel.textAlignment = .center
        detailLabel.numberOfLines = 0
        detailLabel.lineBreakMode = .byWordWrapping
        titleView.addSubview(detailLabel)
        detailLabel.snp.makeConstraints { make in
            make.left.right.equalTo(titleLabel)
            make.top.equalTo(titleLabel.snp.bottom).offset(3)
        }
        
        qrImgView.frame = CGRectMake(0, titleView.bottom + pixw(p:36), 255, 255)
        let imgUrl = self.dic["url"] as? String ?? ""
        qrImgView.contentMode = .scaleAspectFit
        
         let imgUrl1 = imgUrl.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
        qrImgView.yy_setImage(with: URL(string: imgUrl1 ?? ""), options: .showNetworkActivity)
        qrImgView.centerX = titleView.centerX
        qrImgView.layer.cornerRadius = pixw(p:5)
        contentView.addSubview(qrImgView)
        
        let shareBtn = UIButton(type: .custom)
        shareBtn.layer.cornerRadius = pixw(p:10)
        shareBtn.setTitle(LocalizedString("分享"), for:.normal)
        shareBtn.setImage(UIImage(systemName: "square.and.arrow.up"), for: .normal)
        shareBtn.tintColor = UIColor.white
        shareBtn.setTitleColor(UIColor.white, for: .normal)
        shareBtn.titleLabel?.font = MY_SCALE_BoldFont(14)
        shareBtn.setButtonImageAlignmentStyle(.top, imageAndLabelSpace: pixw(p:3))
        shareBtn.tag = 1000
        shareBtn.addTarget(self, action: #selector(btnClick(sender: )), for: .touchUpInside)
        shareBtn.backgroundColor = MYColor.color(withHexString: "#FDBB01")
        self.view.addSubview(shareBtn)
        shareBtn.snp.makeConstraints { make in
            make.left.right.equalTo(contentView)
            make.top.equalTo(contentView.snp.bottom).offset(pixw(p:20))
            make.height.equalTo(pixw(p:50))
        }
        
        let downBtn = UIButton(type: .custom)
        downBtn.layer.cornerRadius = 10
        downBtn.setTitle(LocalizedString("下载"), for:.normal)
        downBtn.setImage(UIImage(systemName: "square.and.arrow.down"), for: .normal)
        downBtn.tintColor = UIColor.white
        downBtn.setTitleColor(UIColor.white, for: .normal)
        downBtn.titleLabel?.font = MY_SCALE_BoldFont(14)
        downBtn.setButtonImageAlignmentStyle(.top, imageAndLabelSpace: pixw(p:3))
        downBtn.tag = 1001
        downBtn.addTarget(self, action: #selector(btnClick(sender: )), for: .touchUpInside)
        downBtn.backgroundColor = MYBlue
        self.view.addSubview(downBtn)
        downBtn.snp.makeConstraints { make in
            make.left.right.height.equalTo(shareBtn)
            make.top.equalTo(shareBtn.snp.bottom).offset(pixw(p:15))
        }
    }
    
    @objc fileprivate func navClick(sender:UIButton){
        if sender.tag == 1000 {
            self.navigationController?.popToRootViewController(animated: true)
            if editNum >= 1 {
                func keyWindow() -> UIWindow {
                       if #available(iOS 15.0, *) {
                           let keyWindow = UIApplication.shared.connectedScenes
                               .map({ $0 as? UIWindowScene })
                               .compactMap({ $0 })
                               .first?.windows.first ?? UIWindow()
                           return keyWindow
                       }else {
                           let keyWindow = UIApplication.shared.windows.first ?? UIWindow()
                           return keyWindow
                       }
                   }
                (keyWindow().rootViewController as! TabBarController).selectedIndex = 1
            }
        }else{
            var custom_parametersDic = Helper.dictionary(withJsonString: self.dic["customParameterStr"] as? String ?? "")
            if custom_parametersDic.keys.count < 1 {
                custom_parametersDic = Helper.dictionary(withJsonString: self.dic["custom_parameters_str"] as? String ?? "")
            }
            
            let controller = EditCodeController()
            controller.editDic = self.dic
            self.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    override func backItemClick(_ sender: Any) {
        if self.dic["id"] != nil {
            self.navigationController?.popToRootViewController(animated: true)
        }else{
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc fileprivate func btnClick(sender:UIButton){
        if sender.tag == 1000 {
            if self.dic["demo_url"] != nil {
                self.newLoadData(url: self.dic["demo_url"] as! String)
            }else{
                self.newLoadData(url: self.dic["url"] as! String)
            }
        }else if sender.tag == 1001 {
            let img = qrImgView.image
            if img != nil {
                UIImageWriteToSavedPhotosAlbum(img!, self, nil, nil)
                QMUITips.showSucceed(LocalizedString("保存成功"))
            }else{
                QMUITips.showError(LocalizedString("请稍后再试"))
            }
        }
    }
    
    fileprivate func newLoadData(url:String){
        let urls = url.components(separatedBy: "/")
        let filePath = self.videoFilePath().appending(urls.last!)
        let fileExists = FileManager.default.fileExists(atPath: filePath)
        if fileExists {
            try? FileManager.default.removeItem(atPath: filePath)
        }
        let manager = AFHTTPSessionManager(baseURL: nil)
        let request = URLRequest(url: URL(string: url)!)
        let downTask = manager.downloadTask(with: request) { downloadProgress in
            
        } destination: { targetPath, response in
            return URL(fileURLWithPath: filePath)
        } completionHandler: { response, filePath, error in
            self.imgTempPath = filePath!.absoluteString
            self.exportQR(urlStr: filePath!.absoluteString)
            
        }
        downTask.resume()
    }
    
    fileprivate func videoFilePath() ->String {
        let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let filePath = path!.appending("clockin_movie_file")
        let isExists = FileManager.default.fileExists(atPath: filePath)
        if isExists == false {
            try? FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: true)
        }
        return filePath
    }
    
    fileprivate func exportQR(urlStr:String){
        let url = URL(string: urlStr)
        document = UIDocumentInteractionController(url: url!)
        document.delegate = self
        let canOpen = document.presentOpenInMenu(from: self.view.bounds
                                                 , in: self.view, animated: true)
        if canOpen == false {
            
        }
    }
}

extension FileDetailController{
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
    
    func documentInteractionControllerViewForPreview(_ controller: UIDocumentInteractionController) -> UIView? {
        return self.view
    }
    
    func documentInteractionControllerRectForPreview(_ controller: UIDocumentInteractionController) -> CGRect {
        return self.view.frame
    }
    
    func documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) {
        try? FileManager.default.removeItem(atPath: self.imgTempPath)
    }
}
